package com.shouxin.attendance.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shouxin.attendance.R;
import com.shouxin.attendance.constants.PrefKey;
import com.shouxin.attendance.database.DBHelper;
import com.shouxin.attendance.network.CommonCallback;
import com.shouxin.attendance.network.HttpAction;
import com.shouxin.attendance.network.ServiceFactory;
import com.shouxin.attendance.utils.SharedPref;
import com.shouxin.attendance.utils.UIUtils;
import com.shouxin.attendance.utils.Utils;

import org.apache.log4j.Logger;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

/**
 * A login screen that offers login via phone/password.
 */
public class LoginActivity extends BaseActivity {

	private static final Logger logger = Logger.getLogger(LoginActivity.class);

	// UI references.
	private EditText mAccountView;

	private EditText mPasswordView;

	private CheckBox mAutoLogin;

	@Override
	public void setContentView() {
		setContentView(R.layout.activity_login);
	}

	@Override
	public void initUIViews() {
		mAccountView = (EditText) findViewById(R.id.account);
		mPasswordView = (EditText) findViewById(R.id.password);
		mAutoLogin = (CheckBox) findViewById(R.id.auto_login);
	}

	@Override
	public void initData() {

	}

	@Override
	public void bindEvents() {
		String phoneNumber = SharedPref.getString(PrefKey.ACCOUNT, "");
		mAccountView.setText(phoneNumber);
		mAccountView.setSelection(phoneNumber.length());

		String password = SharedPref.getString(PrefKey.PASSWORD, "");
		if (!TextUtils.isEmpty(password)) {
			mAutoLogin.setChecked(true);
			mPasswordView.setText(password);
			attemptLogin(null);
		}

		mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
			@Override
			public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
				if (id == R.id.login || id == EditorInfo.IME_NULL) {
					attemptLogin(null);
					return true;
				}
				return false;
			}
		});
	}

	/**
	 * Attempts to sign in or register the account specified by the login form.
	 * If there are form errors (invalid email, missing fields, etc.), the
	 * errors are presented and no actual login attempt is made.
	 */
	public void attemptLogin(View view) {
		// Reset errors.
		mAccountView.setError(null);
		mPasswordView.setError(null);

		// Store values at the time of the login attempt.
		String account = mAccountView.getText().toString();
		String password = mPasswordView.getText().toString();

		boolean cancel = false;
		View focusView = null;

		// Check for a valid password, if the user entered one.
		if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
			mPasswordView.setError(getString(R.string.error_invalid_password));
			focusView = mPasswordView;
			cancel = true;
		}

		// Check for a valid email address.
		if (TextUtils.isEmpty(account)) {
			mAccountView.setError(getString(R.string.error_field_required));
			focusView = mAccountView;
			cancel = true;
		}/* else if (!Utils.isPhoneValid(phone)) {
	        mAccountView.setError(getString(R.string.error_invalid_phone));
            focusView = mAccountView;
            cancel = true;
        }*/

		if (cancel) {
			focusView.requestFocus();
		} else {
			UIUtils.showLoading(this, "正在登录...");
			doLogin(account, password);
		}
	}

	private void doLogin(final String account, final String password) {
		JSONObject requestParams = new JSONObject();
		requestParams.put("account", account);
		requestParams.put("password", Utils.md5(password));
		requestParams.put("ver", Utils.getAppVersionName());
		requestParams.put("client", "1");

		HttpAction httpAction = ServiceFactory.get().getService(HttpAction.NAME);
		if (httpAction != null) {
			logger.debug("requestParams =>" + requestParams.toJSONString());
			httpAction.login(requestParams.toJSONString(), this, new CommonCallback() {
				@Override
				public void onFailure(Call call, IOException e) {
					super.onFailure(call, e);
					mHandler.sendEmptyMessage(DIALOG_DISMISS);

					mHandler.sendMessage(mHandler.obtainMessage(SHOW_TOAST, "登录失败，请重试！"));
				}

				@Override
				public void onResponse(Call call, Response response) throws IOException {
					mHandler.sendEmptyMessage(DIALOG_DISMISS);
					SharedPref.putString(PrefKey.ACCOUNT, account);
					SharedPref.putString(PrefKey.PASSWORD, password);
					SharedPref.putBoolean(PrefKey.AUTO_LOGIN, mAutoLogin.isChecked());

					loginResponse(JSON.parseObject(response.body().string()));
				}
			});
		}
	}

	private void loginResponse(JSONObject response) {
		logger.debug("response => " + response.toString());
		int ret = response.getIntValue("ret");
		logger.debug("ret => " + ret);
		if (ret == 1) {
			logger.error("请求参数错误！");
			mHandler.sendMessage(mHandler.obtainMessage(SHOW_TOAST, "请求参数错误用户名或密码错误，请重试！"));
			return;
		} else if (ret == 7101) {
			logger.error("用户名或密码错误！");
			mHandler.sendMessage(mHandler.obtainMessage(SHOW_TOAST, "用户名或密码错误，请重试！"));
			return;
		} else if (ret == 7102) {
			logger.error("登录失败！");
			mHandler.sendMessage(mHandler.obtainMessage(SHOW_TOAST, "登录失败，请重试！"));
			return;
		}
		JSONObject data = response.getJSONObject("data");
		if (data == null || data.isEmpty()) {
			logger.error("平台返回数据异常！");
			mHandler.sendMessage(mHandler.obtainMessage(SHOW_TOAST, "平台返回数据异常，请重试！"));
			return;
		}

		SharedPref.putBoolean(PrefKey.HAS_LOGGED, true);
		String token = data.getString("token");
		SharedPref.putString(PrefKey.TOKEN, token);

		// 创建数据库
		DBHelper.getInstance().initDB(this, mAccountView.getText().toString());

		loginSuccess();
	}

	private void loginSuccess() {
		Intent intent = new Intent();
		intent.setClass(this, MainActivity.class);
		startActivity(intent);
		finish();
	}

	private boolean isPasswordValid(String password) {
		return password.length() > 1;
	}

}

